package com.handu.luna.boss.controller.support;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;

import com.handu.luna.boss.controller.BossModel;
import com.handu.luna.boss.controller.LoginController;
import com.handu.luna.core.domain.admin.AdminControllerCategory;
import com.handu.luna.core.domain.admin.AdminControllerDescription;

@Aspect
@Component
public class ControllerNameAspector {
	protected Log logger = LogFactory.getLog(this.getClass());
	
    @Around("execution(* com.handu.luna.boss.controller.*.*(..))")  
    public Object processTx(ProceedingJoinPoint joinPoint) throws java.lang.Throwable {  

        Object result = joinPoint.proceed(joinPoint.getArgs());  
        
        if(result instanceof BossModel){
        	BossModel model = (BossModel)result;
        	if(model.getViewName() == null || (model.getViewName()!= null && !model.getViewName().contains("redirect:"))){
	        	logger.debug(joinPoint.getTarget().getClass().getSimpleName());
	        	if(!(joinPoint.getTarget() instanceof LoginController)){
		        	String controllerName = joinPoint.getTarget().getClass().getSimpleName().replace("Controller", "");
		        	logger.debug("controllerName:" + controllerName);
		        	String actionName = joinPoint.getSignature().getName();
		        	logger.debug("actionName:" + actionName);
		        	
		        	AdminControllerDescription description = AdminControllerCategory.getByName(controllerName);
		        	if(description == null){
		        		description = AdminControllerDescription.createErrorDescription();
		        	}
		        	model.setControllerDescription(description);
		        	model.setActionName(description.getActionName(actionName));
		        	model.setActionDescription(description.getActionDescription(actionName));
	        	}
        	}
        }

        return result;  
    }  
}
